﻿using System.Collections.Generic;
using System.Linq;
using AbcCorp.DTO;
using DAO.EntityModel;

namespace AbcCorp.DAO
{
    public class CategoryDao
    {
        #region Variable
        /// <summary>
        /// Khai báo tượng entity model
        /// </summary>
        private readonly ABCCorpEntities _abcCorpEntities = new ABCCorpEntities();
        #endregion

        #region Methods
        /// <summary>
        /// Lấy toàn bộ danh mục 
        /// </summary>
        /// <returns>CategoryDto</returns>
        public IList<CategoryDto> GetCategories()
        {
            IList<CategoryDto> lstCategory = new List<CategoryDto>();
            var categories = from cat in _abcCorpEntities.Categories
                             select cat;
            if (categories.FirstOrDefault() == null) return null;
            foreach (var item in categories)
            {
                var categorydto = new CategoryDto();
                CopyObject<Category, CategoryDto>.CopyProperties(item, categorydto); 
                lstCategory.Add(categorydto);
            }
            return lstCategory;
        }

        /// <summary>
        /// Lấy danh mục dựa vào mã danh mục
        /// </summary>
        /// <param name="catid">Mã danh mục</param>
        /// <returns>CategoryDto</returns>
        public CategoryDto GetCategory(int catid)
        {
            var categoryinfo = from cat in _abcCorpEntities.Categories.Where(c => c.CategoryID.Equals(catid))
                           select cat;
            var category = categoryinfo.SingleOrDefault();
            if(category== null) return null;
            var categoryDto = new CategoryDto();
            CopyObject<Category, CategoryDto>.CopyProperties(category, categoryDto); 
            return categoryDto;
        }

        /// <summary>
        /// Thêm danh mục sản phẩm
        /// </summary>
        /// <param name="newCategory">Thông tin của danh mục mới</param>
        public bool AddCategory(CategoryDto newCategory)
        {
            var category = new Category();
            CopyObject<CategoryDto, Category>.CopyProperties(newCategory, category);
            _abcCorpEntities.Categories.AddObject(category);
            return _abcCorpEntities.SaveChanges() > 0;
        }
        #endregion
    }
}
